/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.buzzwords.behaviors;


import com.buzzwords.exceptions.DuplicateEntryException;
import com.buzzwords.domain.User;
import java.util.List;

/**
 *
 * @author potlow
 */
public abstract class UserBehavior extends DatabaseBehavior {

    @Override
    public boolean create(Object value) throws DuplicateEntryException{
        User user;
        if (value instanceof User) {
            user = (User) value;
        } else {
            throw new IllegalArgumentException("Search value must be a User");
        }

        List<Object> users = read(user.getEmail());

        if (!users.isEmpty()) {
            user.setId(((User)users.get(0)).getId());
            throw new DuplicateEntryException("User: " + user.getEmail() + " has already been found in the datatbase",
                    "Email address belongs to a registered user. Try using the forgot password tab to retrieve password");
        }

        return persist(user);
    }

    @Override
    abstract public List<Object> read(Object value);

    @Override
    public boolean update(Object value) {
        User user;
        if (value instanceof User) {
            user = (User) value;
        } else {
            throw new IllegalArgumentException("Search value must be a User");
        }

        return merge(user);
    }

    @Override
    public boolean delete(Object value) {
        User user;
        if (value instanceof User) {
            user = (User) value;
        } else {
            throw new IllegalArgumentException("Search value must be a User");
        }

        return remove(user);
    }

}
